/**
 * Filename: YNBannerWebActivity.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/18 1:03
 */
package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.utils.SnackBarUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.utils.YNInviteSecret;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * BannerWeb页
 */
public class YNBannerWebActivity extends BaseActivity {
    private PopupWindow menuWindow;
    private Toolbar mToolbar;
    private WebView banner_webView;
    private ProgressDialog mProgressDialog;
    private String tarUrl;
    private String shareUrl = "";
    private String shareTitle = "";
    private String shareDesc = "";
    private String shareImage = "";
    private BaseUiListener listener;
    private String inviteKey;
    private Tencent mTencent;
    private View view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.yn_activity_banner_web);
        initView();
        mTencent = Tencent.createInstance(getString(R.string.QQ_APP_ID), this.getApplicationContext());
        listener = new BaseUiListener();
        shareImage = application.getCurUser().getUpic();
        //shareTitle = getString(R.string.yn_content_share_title);
        //shareDesc = getString(R.string.yn_friends_share_title);
    }


    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.banner_web_toolbar);
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.drawable.ic_return);
        banner_webView = (WebView) findViewById(R.id.banner_webView);
        banner_webView.setDrawingCacheEnabled(true);
        //banner_webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        banner_webView.getSettings().setDefaultTextEncodingName("utf-8");
        banner_webView.getSettings().setJavaScriptEnabled(true);
        banner_webView.addJavascriptInterface(new WebAppInterface(), "Android");
        // 载入页面：本地html资源文件
        //  banner_webView.loadUrl("file:///android_asset/sample.html");
        tarUrl = getIntent().getStringExtra(CommonConstants.YNBANNERURL);
        banner_webView.loadUrl(doInvateKey(tarUrl));
        banner_webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                view.loadUrl(url);
                return true;
            }
        });
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_DATA);
        banner_webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    // 网页加载完成
                    mProgressDialog.dismiss();
                } else {
                    // 加载中
                    mProgressDialog.show();
                }
            }
        });
    }

    private String doInvateKey(String loadurl) {
        String invite = CommonConstants.YNS_USER_ID + "=" + application.getCurID();
        // String invite = CommonConstants.YNS_USER_ID + "=" + 16;
        try {
            inviteKey = YNInviteSecret.encryptDES(invite, getString(R.string.UNKNOW_ID));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return loadurl + "?code=" + inviteKey + "&time=" + System.currentTimeMillis();
        //return loadurl + "?code=" + inviteKey;
    }


    private class BaseUiListener implements IUiListener {
        protected void doComplete(JSONObject values) {
        }

        @Override
        public void onComplete(Object o) {
            showLog(o.toString());
            doComplete((JSONObject) o);
        }

        @Override
        public void onError(UiError e) {
            showLog("onError:====code:" + e.errorCode + ", msg:"
                    + e.errorMessage + ", detail:" + e.errorDetail);
        }

        @Override
        public void onCancel() {
            showLog("onCancel=====");
        }
    }

    public class WebAppInterface {

        @JavascriptInterface
        public void doJieTu() {
            saveBitmap(captureWebViewVisibleSize());
            SnackBarUtils.makeLong(mToolbar, "截图已保存到本地").show();
        }

        @JavascriptInterface
        public void doShare(String sharestrl, String sharetitle, String sharedesc, String shareimage) {
            shareUrl = sharestrl;
            shareTitle = sharetitle;
            shareDesc = sharedesc;
            if (!StringUtils.isEmpty(shareimage)) {
                shareImage = shareimage;
            }
            menuWindow = new SelectPicPopupWindow(YNBannerWebActivity.this, YNBannerWebActivity.this.findViewById(R.id.share_main));
        }
    }

    private Bitmap captureWebViewVisibleSize() {
        Bitmap bmp = banner_webView.getDrawingCache();
        return bmp;
    }


    private void saveBitmap(Bitmap bm) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "yinian/YiNian");
        if (!file.exists()) {
            file.mkdirs();
        }
        File f = new File(file.getPath() + "/", System.currentTimeMillis() + ".jpg");
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(f);
        intent.setData(uri);
        sendBroadcast(intent);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        public void onClick(View v) {
            view.startAnimation(AnimationUtils.loadAnimation(YNBannerWebActivity.this,
                    R.anim.push_bottom_out));
            menuWindow.dismiss();
            UMWeb web = new UMWeb(shareUrl);
            web.setTitle(shareTitle);
            web.setThumb(new UMImage(YNBannerWebActivity.this, shareImage));  //缩略图
            web.setDescription(shareDesc);
            switch (v.getId()) {
                case R.id.btn_share_qq:
                    new ShareAction(YNBannerWebActivity.this).setPlatform(SHARE_MEDIA.QQ).setCallback(umShareListener)
                            .withMedia(web)
                            .share();
                    break;
                case R.id.btn_share_weixin:
                    new ShareAction(YNBannerWebActivity.this).setPlatform(SHARE_MEDIA.WEIXIN).setCallback(umShareListener)
                            .withText(shareDesc)
                            .withMedia(web)
                            .share();
                    break;
                case R.id.btn_share_friends:
                    new ShareAction(YNBannerWebActivity.this).setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE).setCallback(umShareListener)
                            .withMedia(web)
                            .share();
                    break;
                default:
                    break;
            }
        }
    };
    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {

        }

        @Override
        public void onResult(SHARE_MEDIA platform) {

            if (platform.name().equals("WEIXIN_FAVORITE")) {
                Toast.makeText(YNBannerWebActivity.this, platform + " 收藏成功啦", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(YNBannerWebActivity.this, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(YNBannerWebActivity.this, platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                com.umeng.socialize.utils.Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(YNBannerWebActivity.this, platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };


    public class SelectPicPopupWindow extends PopupWindow {
        public SelectPicPopupWindow(Context mContext, View parent) {
            view = View
                    .inflate(mContext, R.layout.yn_web_share, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in));
            setWidth(LinearLayout.LayoutParams.FILL_PARENT);
            setHeight(UIHelper.dip2px(YNBannerWebActivity.this, 220));
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            TextView bt1 = (TextView) view
                    .findViewById(R.id.btn_share_qq);
            TextView bt2 = (TextView) view
                    .findViewById(R.id.btn_share_weixin);
            TextView bt3 = (TextView) view.findViewById(R.id.btn_share_friends);
            Button bt4 = (Button) view
                    .findViewById(R.id.btn_cancel);
            bt1.setOnClickListener(itemsOnClick);
            bt2.setOnClickListener(itemsOnClick);
            bt3.setOnClickListener(itemsOnClick);
            bt4.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }

    // 友盟统计
    public void onResume() {
        super.onResume();
//        banner_webView.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
//        banner_webView.reload();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
